import java.util.Arrays;

/**
 * @author LKQ
 * @date 2021/12/30 15:27
 * @description
 */
public class Solution2 {
    public static void main(String[] args) {
        Solution2 solution2 = new Solution2();
        int[] nums = {1, 1, 1, 0};
        System.out.println(solution2.threeSumClosest(nums, -100));
    }

    public int threeSumClosest(int[] nums, int target) {
        int n = nums.length, ans = Integer.MAX_VALUE, res = 0;
        Arrays.sort(nums);
        // 枚举a
        for (int i = 0; i < n - 2; i++) {
            // 去重
            if (i > 0 && nums[i] == nums[i-1]) {
                continue;
            }
            int partSum = target - nums[i];
            int left = i + 1, right = n - 1;
            while (left < right) {
                // 保留比较之前的值
                int last = ans;
                ans = Math.min(Math.abs(partSum - nums[left] - nums[right]), ans);
                if (ans != last) {
                    // 找到更接近的
                    res = nums[i] + nums[left] + nums[right];
                }
                if (nums[left] + nums[right] == partSum) {
                    res = nums[i] + nums[left] + nums[right];
                    break;
                }else if (nums[left] + nums[right] < partSum){
                    left++;
                }else {
                    right--;
                }
            }
        }
        return res;
    }
}
